import Vue from "vue"
import Vuex from 'vuex'
import { login, info } from '../api/user'
import { resetToken, setToken } from "../util/auth"
import { status } from "../util/status"
import wsConnect from '../ws/index'

Vue.use(Vuex)

export default new Vuex.Store({
    state: {
        token: '',
        connecting: false,
        header: {
            title: '微信',
            visible: true,
        },
        user: {
            avatar: '',
            nickname: '',
        }
    },
    mutations: {
        SET_HEADER(state, header) {
            state.header = header;
        },
        SET_USER(state, user) {
            state.user = user;
        },
        SET_TOKEN(state, token) {
            state.token = token;
        },
        SET_CONNECTING(state, bool) {
            state.connecting = bool;
        } 
    },

    actions: {
        async login({ commit, dispatch } ,payload) {
            const { username, password } = payload
            const res = await login(username, password)
            const resContent = res.data;
            if (resContent.status === status.SUCCESS) {
                const token = resContent.data[import.meta.env.VITE_TOKEN]
                setToken(token)
                commit('SET_TOKEN', token)
                // 这里连接socket，不要阻塞后续代码
                dispatch('connect')
            }
            return resContent;
        },
        async info({ commit, dispatch }) {
            const res = await info()
            const resContent = res.data
            if (resContent.status === status.SUCCESS) {
                commit('SET_USER', resContent.data);
                dispatch('connect')
            }
            return resContent;
        },
        logout({ commit }) {
            resetToken()
            commit('SET_TOKEN', '')
            commit('SET_CONNECTING', false)
            commit('SET_USER', {
                avatar: '',
                nickname: '',
            })
            wsConnect.close()
        },
        async connect({ commit, state }) {
            try {
                await wsConnect.connect({
                    token: state.token,
                })
                commit('SET_CONNECTING', true);
            } catch (err) {
                commit('SET_CONNECTING', false);
            }
        }
    }

})